using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;

namespace UselessExplorer
{
    public partial class frmVB6Documenter : Form
    {
        #region Declarations

        const string PROJECTFILE = ".vbp";
        const string EXPRESSION = "=";
        const string FORMS = "Form" + EXPRESSION;
        const string UC = "UserControl" + EXPRESSION;
        const string MOD = "Module" + EXPRESSION;
        const string CLASS = "Class" + EXPRESSION;
        const string OBJECT = "Object" + EXPRESSION;
        const string REFERENCE = "Reference" + EXPRESSION;
        const string SUB_KEYWORD_PRIVATE = "Private Sub";
        const string SUB_KEYWORD_PUBLIC = "Public Sub";
        const string PROPERTY_KEYWORD_GET = "Public Property Get";
        const string PROPERTY_KEYWORD_SET = "Public Property Set";
        const string FUNCTION_KEYWORD_PUBLIC = "Public Function";
        const string FUNCTION_KEYWORD_PRIVATE = "Private Function";

        enum SubContentHeading
        {
            Properties,
            Functions,
            SubRoutines
        }

        private string initialFilePath;
        public string InitialFilePath
        {
            get { return initialFilePath; }
            set { initialFilePath = value; }
        }

        #endregion

        #region Constructor

        public frmVB6Documenter()
        {
            InitializeComponent();

            cleanWindow();

        }

        #endregion

        #region Event Methods

        private void btnGetDetails_Click(object sender, EventArgs e)
        {
            tbFilePath.Enabled = false;

            cleanWindow();
            getProjectDetails();
            

            label2.Text = lbForms.Items.Count.ToString();
            label3.Text = lbModules.Items.Count.ToString();
            label4.Text = lbClasses.Items.Count.ToString();
            label5.Text = lbUserControls.Items.Count.ToString();

            if (lbForms.Items.Count != 0 || lbProperty.Items.Count != 0 || lbModules.Items.Count != 0 || lbFunction.Items.Count != 0)
            {
                this.btnGenerateDoc.Enabled = true;
            }
            else
            {
                this.btnGenerateDoc.Enabled = false;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tbFilePath.Enabled = true;
            cleanWindow();
        }

        private void frmVB6Documenter_Load(object sender, EventArgs e)
        {
            this.Text = UselessExplorer.Properties.UselessResources.frmVB6DocTitle;
            this.btnGenerateDoc.Enabled = false;
        }

        private void btnBrowseFolder_Click(object sender, EventArgs e)
        {
            if(tbFilePath.Text == String.Empty)
                    folderBrowserDialog1.SelectedPath = tbFilePath.Text;

            DialogResult = folderBrowserDialog1.ShowDialog();
            if (DialogResult == DialogResult.OK)
            {
                tbFilePath.Text = folderBrowserDialog1.SelectedPath;
                getProjectFile();
            }
        }

        private void lbForms_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                getInnerDetails(lbForms.SelectedItem.ToString());
            }
            catch (Exception)
            {

            }
        }

        private void lbModules_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                getInnerDetails(lbModules.SelectedItem.ToString());
            }
            catch (Exception)
            {
            }
        }

        private void lbClasses_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                getInnerDetails(lbClasses.SelectedItem.ToString());
            }
            catch (Exception)
            {
            }
        }

        private void lbUserControls_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                getInnerDetails(lbUserControls.SelectedItem.ToString());
            }
            catch (Exception)
            {
            }
        }

        private void btnGenerateDoc_Click(object sender, EventArgs e)
        {
            lblFinalStatus.Text = "Generating Document.. ";
            prepareWordDocument();
            fillDataToWordDoc();
            lblFinalStatus.Text = "Document Generated";
        }

        #endregion

        #region User Defined Methods


        object oMissing = System.Reflection.Missing.Value;
        // object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

        //Start Word and create a new document.
        //Word._Application oWord;
        //Word._Document oDoc;

        /// <summary>
        /// To get the details about the FORM, MODULES, USER CONTROLS etc
        /// </summary>
        /// 
        private void getInnerDetails(string modValue)
        {
            try
            {
                lbSubRoutines.Items.Clear();
                lbProperty.Items.Clear();
                lbFunction.Items.Clear();


                string modPath = InitialFilePath + @"\" + modValue;
                string line = null;

                StreamReader file = new System.IO.StreamReader(modPath);
                while ((line = file.ReadLine()) != null)
                {
                    if (line.StartsWith(SUB_KEYWORD_PUBLIC) || line.StartsWith(SUB_KEYWORD_PRIVATE))
                    {
                        lbSubRoutines.Items.Add(line);
                    }
                    else if (line.StartsWith(PROPERTY_KEYWORD_GET) || line.StartsWith(PROPERTY_KEYWORD_SET))
                    {
                        lbProperty.Items.Add(line);
                    }
                    else if (line.StartsWith(FUNCTION_KEYWORD_PUBLIC) || line.StartsWith(FUNCTION_KEYWORD_PRIVATE))
                    {
                        lbFunction.Items.Add(line);
                    }

                }
            }
            catch (Exception ex)
            {
                ClsGlobal.Instance.WriteLogs(Logger.LogsCategory.Exception, ex);
                MessageBox.Show("Unable to locate all the project files","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }

            showCount();
        }

        private void cleanWindow()
        {
            lbClasses.Items.Clear();
            lbForms.Items.Clear();
            lbModules.Items.Clear();
            lbUserControls.Items.Clear();
            lbSubRoutines.Items.Clear();
            lbProperty.Items.Clear();
            lbFunction.Items.Clear();

            this.btnGenerateDoc.Enabled = false;

            label2.Text = string.Empty;
            label3.Text = string.Empty;
            label4.Text = string.Empty;
            label5.Text = string.Empty;
            label6.Text = string.Empty;
            label7.Text = string.Empty;
            label8.Text = string.Empty;
            lblFinalStatus.Text = string.Empty;
        }

        private void showCount()
        {
            label6.Text = lbSubRoutines.Items.Count.ToString();
            label7.Text = lbProperty.Items.Count.ToString();
            label8.Text = lbFunction.Items.Count.ToString();
        }

        private void getProjectFile()
        {
            if (tbFilePath.Text != "")
            {
                InitialFilePath = tbFilePath.Text;
                string[] files = Directory.GetFiles(InitialFilePath);

                foreach (string file in files)
                {
                    DirectoryInfo dif = new DirectoryInfo(file);
                    if (dif.Extension.Equals(PROJECTFILE))
                    {
                        cbProjectName.Items.Add(dif.Name);
                    }
                }
            }
            else
            {
                tbFilePath.Enabled = true;
                MessageBox.Show("No Project File Path Specified");
            }
        }

        private void getProjectDetails()
        {
            try
            {
                string line;
                int count = 0;
                string[] temp = new string[2];
                string[] clsTemp = new string[4];
                string[] modTemp = new string[4];

                if (cbProjectName.SelectedItem.ToString() != null)
                {
                    StreamReader file = new System.IO.StreamReader(InitialFilePath + @"\" + cbProjectName.SelectedItem);
                    while ((line = file.ReadLine()) != null)
                    {
                        if (line.StartsWith(FORMS))
                        {
                            temp = line.Split('=');
                            lbForms.Items.Add(temp[1]);
                        }
                        else if (line.StartsWith(UC))
                        {
                            temp = line.Split('=');
                            lbUserControls.Items.Add(temp[1]);
                        }
                        else if (line.StartsWith(MOD))
                        {
                            modTemp = line.Split('=', ';', ' ');
                            lbModules.Items.Add(modTemp[3]);
                        }
                        else if (line.StartsWith(CLASS))
                        {
                            clsTemp = line.Split('=', ';', ' ');
                            lbClasses.Items.Add(clsTemp[3]);
                        }
                        else if (line.StartsWith(OBJECT))
                        {
                            addProjectProperties(line,OBJECT); 
                        }
                        else if (line.StartsWith(REFERENCE))
                        {
                            addProjectProperties(line,REFERENCE);
                        }

                        count++;
                        
                    }

                    dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Please Select a valid VB project", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                ClsGlobal.Instance.WriteLogs(Logger.LogsCategory.Exception, ex);
            }
        }


        private void prepareWordDocument()
        {
            //oWord = new Word.Application();
            //oWord.Visible = true;
            //oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        }

        private void fillDataToWordDoc()
        {
            int _MainHeading = 4;
            for (int index = 1; index <= _MainHeading; index++)
            {
                printMainHeading(index);
                getSubContent(index);
            }
        }

        private void getSubContent(int parentHeading)
        {

            // Sub Content
            //Word.Paragraph oParaSub;
            //oParaSub = oDoc.Content.Paragraphs.Add(ref oMissing);
            //oParaSub.Range.Font.Bold = 2;
            //oParaSub.Range.Font.Size = 11;
            //oParaSub.Format.SpaceAfter = 15;    //24 pt spacing after paragraph.
            //oParaSub.Format.LeftIndent = 10.5F;
            //oParaSub.Range.InsertParagraph();
            
            //switch (parentHeading)
            //{
            //    case 1:
            //        foreach (string item in lbForms.Items)
            //        {
            //            oParaSub.Range.InsertBefore(item + System.Environment.NewLine);
            //            getSubContentDetails(item);
            //        }
            //        break;
            //    case 2:
            //        foreach (string item in lbModules.Items)
            //        {
            //            oParaSub.Range.InsertBefore(item + System.Environment.NewLine);
            //            getSubContentDetails(item);
            //        }
            //        break;
            //    case 3:
            //        foreach (string item in lbClasses.Items)
            //        {
            //            oParaSub.Range.InsertBefore(item + System.Environment.NewLine);
            //            getSubContentDetails(item);
            //        }
            //        break;
            //    case 4:
            //        foreach (string item in lbUserControls.Items)
            //        {
            //            oParaSub.Range.InsertBefore(item + System.Environment.NewLine);
            //            getSubContentDetails(item);
            //        }
            //        break;
            //}
        }

        private void printMainHeading(int mainHeading)
        {
            //Insert a paragraph at the beginning of the document.
            //Word.Paragraph oPara1;
            //oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
            //oPara1.Range.Font.Bold = 1;
            //oPara1.Range.Font.Size = 14;
            //oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
            //oPara1.Range.InsertParagraphAfter();

            //switch (mainHeading)
            //{
            //    case 1:
            //        oPara1.Range.Text = "FORMS";
            //        break;
            //    case 2:
            //        oPara1.Range.Text = "MODULES";
            //        break;
            //    case 3:
            //        oPara1.Range.Text = "CLASS";
            //        break;
            //    case 4:
            //        oPara1.Range.Text = "USER CONTROLS";
            //        break;

            //}
        }


        // Sub Content Details
        //Word.Paragraph oParaSubDetails = null;
        //Word.Paragraph subContentHeading = null;

        private void getSubContentDetails(string modValue)
        {
            //oParaSubDetails = oDoc.Content.Paragraphs.Add(ref oMissing);
            //oParaSubDetails.Range.Font.Bold = 0;
            //oParaSubDetails.Range.Font.Size = 9;
            //oParaSubDetails.Format.SpaceAfter = 5;    //24 pt spacing after paragraph.
            //oParaSubDetails.Format.LeftIndent = 25.5F;

            //string modPath = InitialFilePath + @"\" + modValue;
            //StreamReader file = new System.IO.StreamReader(modPath);

            //getSubContentDetails(file);
        }
        

        private void getSubContentDetails(StreamReader file)
        {
            string line = null;

            ArrayList pData = new ArrayList();
            ArrayList fData = new ArrayList();
            ArrayList sbData = new ArrayList();
            
            while ((line = file.ReadLine()) != null)
            {
                if (line.StartsWith(PROPERTY_KEYWORD_GET) || line.StartsWith(PROPERTY_KEYWORD_SET))
                {
                    pData.Add(line);
                }
                else if (line.StartsWith(FUNCTION_KEYWORD_PUBLIC) || line.StartsWith(FUNCTION_KEYWORD_PRIVATE))
                {
                    fData.Add(line);
                }
                else if (line.StartsWith(SUB_KEYWORD_PUBLIC) || line.StartsWith(SUB_KEYWORD_PRIVATE))
                {
                    sbData.Add(line);
                }
            }
           

            foreach (string property in pData)
            {
                // oParaSubDetails.Range.InsertBefore(property + System.Environment.NewLine);
            }

           
            foreach (string function in fData)
            {
                // oParaSubDetails.Range.InsertBefore(function + System.Environment.NewLine);
            }

           
            foreach (string subr in sbData)
            {
                // oParaSubDetails.Range.InsertBefore(subr + System.Environment.NewLine);
            }
        }

        private void getSubContentHeading(SubContentHeading subHeading)
        {
            //subContentHeading = oDoc.Content.Paragraphs.Add(ref oMissing);
            //subContentHeading.Range.Font.Bold = 1;
            //subContentHeading.Range.Font.Size = 9;
            //subContentHeading.Format.SpaceAfter = 5;    //24 pt spacing after paragraph.
            //subContentHeading.Format.LeftIndent = 23.5F;
            //subContentHeading.Range.InsertParagraph();
            //if (SubContentHeading.Properties == subHeading)
            //{
            //    subContentHeading.Range.InsertAfter("Properties");
            //}
            //else if (SubContentHeading.Functions == subHeading)
            //{
            //    subContentHeading.Range.InsertAfter("Functions");
            //}
            //else if (SubContentHeading.SubRoutines == subHeading)
            //{
            //    subContentHeading.Range.InsertAfter("Subroutines");
            //}
        }

        private void addProjectProperties(string line, string identifier)
        {
            string[] value;

            if (identifier == OBJECT)
            {
                value = line.Split(' ');
                string[] Msg = { OBJECT.Split('=')[0], value[1] };
                dataGridView1.Rows.Add(Msg);
            }
            else
            {
                value = line.Split('#');
                string[] Msg = { REFERENCE.Split('=')[0], value[3] };
                dataGridView1.Rows.Add(Msg);    
            }
        }

        #endregion
    }
}